<template>
  <div class="role-container">
    <el-card class="content-card" :body-style="{ padding: '0' }">
      
      <!-- 搜索区域 -->
      <div class="search-area">
        <div class="search-fields">
          <div class="search-item">
            <label for="roleName">角色名称：</label>
            <el-input 
              id="roleName"
              v-model="searchForm.name" 
              placeholder="请输入角色名称" 
              clearable
              style="width: 200px;"
            />
          </div>
          <div class="search-item">
            <label for="roleCode">角色标识：</label>
            <el-input 
              id="roleCode"
              v-model="searchForm.label" 
              placeholder="请输入角色标识" 
              clearable
              style="width: 200px;"
            />
          </div>
          <div class="search-buttons">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">清空</el-button>
          </div>
        </div>
        <div class="add-role-container">
          <el-button type="primary" @click="handleAddRole">新增角色</el-button>
        </div>
      </div>
      
      <!-- 角色列表表格 -->
      <div class="table-container">
        <div class="table-wrapper">
          <el-table 
            v-loading="loading" 
            :data="roleList" 
            style="width: 100%"
            :header-cell-style="{ textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }"
          >
            <el-table-column 
              type="index" 
              label="序号" 
              width="80"
              :index="(index) => (pagination.page - 1) * pagination.pageSize + index + 1"
            />
            <el-table-column prop="name" label="角色名称" min-width="180" />
            <el-table-column prop="label" label="角色标识" min-width="180" />
            <el-table-column prop="updateTime" label="最后修改时间" min-width="180" />
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <div class="action-buttons">
                  <el-button size="small" type="text" style="color: #409eff;" @click="handleEditRole(row)">修改</el-button>
                  <el-button size="small" type="text" style="color: #409eff;" @click="handleDeleteRole(row.id)">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      
      <!-- 分页控件 -->
      <div class="pagination-container">
        <div class="pagination-info">
          共 {{ pagination.total }} 条记录 第 {{ pagination.page }} / {{ Math.ceil(pagination.total / pagination.pageSize) }} 页
        </div>
        <div class="pagination-controls">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
      
      <!-- 新增/编辑角色对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '新增角色' : '编辑角色'"
        width="500px"
      >
        <el-form :model="formData" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色标识" prop="label">
            <el-input v-model="formData.label" placeholder="请输入角色标识" />
          </el-form-item>
          <el-form-item label="备注说明" prop="remark">
            <el-input v-model="formData.remark" placeholder="请输入备注说明" type="textarea" :rows="3" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { ElMessageBox, ElMessage } from 'element-plus';

// 加载状态
const loading = ref(false);

// 角色列表
const roleList = ref([]);

// 搜索表单
const searchForm = reactive({
  name: '',
  label: ''
});

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
});

// 对话框状态
const dialogVisible = ref(false);
const dialogType = ref('add'); // 'add' 或 'edit'

// 表单数据
const formData = reactive({
  id: '',
  name: '',
  label: '',
  remark: ''
});

// 不再使用模拟数据，直接调用后端API

// 获取角色列表
async function fetchRoleList() {
  loading.value = true;
  try {
    // 调用后端API获取角色列表
    const response = await axios.get('/roles', {
      params: {
        ...searchForm,
        page: pagination.page,
        pageSize: pagination.pageSize
      }
    });
    
    // 处理响应数据
    if (response.data.code === 1) {
      roleList.value = response.data.data.rows || [];
      pagination.total = response.data.data.total || 0;
    } else {
      ElMessage.error(response.data.msg || '获取角色列表失败');
      roleList.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error('获取角色列表失败:', error);
    ElMessage.error('网络错误，请稍后重试');
    roleList.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
}

// 搜索
function handleSearch() {
  pagination.page = 1;
  fetchRoleList();
}

// 重置
function handleReset() {
  searchForm.name = '';
  searchForm.label = '';
  pagination.page = 1;
  fetchRoleList();
}

// 新增角色
function handleAddRole() {
  dialogType.value = 'add';
  formData.id = '';
  formData.name = '';
  formData.label = '';
  formData.remark = '';
  dialogVisible.value = true;
}

// 编辑角色
function handleEditRole(row) {
  dialogType.value = 'edit';
  formData.id = row.id;
  formData.name = row.name;
  formData.label = row.label;
  formData.remark = row.remark || '';
  dialogVisible.value = true;
}

// 删除角色
async function handleDeleteRole(id) {
  try {
    const confirmResult = await ElMessageBox.confirm(
      '确定要删除该角色吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    if (confirmResult === 'confirm') {
      // 调用后端API删除角色
      const response = await axios.delete(`/roles/${id}`);
      
      // 处理响应
      if (response.data.code === 1) {
        ElMessage.success('删除成功');
        fetchRoleList();
      } else {
        ElMessage.error(response.data.msg || '删除失败');
      }
    }
  } catch (error) {
    // 用户取消删除
  }
}

// 提交表单
async function handleSubmit() {
  try {
    // 调用后端API
    let response;
    if (dialogType.value === 'add') {
      // 新增角色
      response = await axios.post('/roles', formData);
    } else {
      // 编辑角色
      response = await axios.put(`/roles/${formData.id}`, formData);
    }
    
    // 处理响应
    if (response.data.code === 1) {
      ElMessage.success(dialogType.value === 'add' ? '新增成功' : '编辑成功');
      dialogVisible.value = false;
      fetchRoleList();
    } else {
      ElMessage.error(response.data.msg || '操作失败');
    }
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败');
  }
}

// 分页大小变化
function handleSizeChange(size) {
  pagination.pageSize = size;
  fetchRoleList();
}

// 当前页码变化
function handleCurrentChange(current) {
  pagination.page = current;
  fetchRoleList();
}

// 组件挂载时获取角色列表
onMounted(() => {
  fetchRoleList();
});
</script>

<style scoped>
.role-container {
  padding: 20px 30px 10px 30px;
  margin-bottom: 0;
}

.search-area {
  padding: 15px 25px 10px 25px;
  background: #ffffff;
  border-bottom: 1px solid #ebeef5;
}

.button-row {
  margin-bottom: 15px;
}

.search-fields {
  display: flex;
  align-items: center;
  gap: 15px;
}

.search-buttons {
  display: flex;
  gap: 10px;
  margin-left: auto;
}

.action-buttons {
  display: flex;
  gap: 2px;
  justify-content: center;
  width: 100%;
}

.search-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-item label {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

.table-container {
  display: flex;
  width: 100%;
  margin: 0;
  padding-top: 5px;
}

.table-wrapper {
  width: 100%;
}

.el-table {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.el-table__inner-wrapper {
  border: none;
  border-radius: 4px;
}

.el-table__header th {
    background-color: #f5f7fa;
    font-weight: 600;
    color: #303133;
    border-bottom: 1px solid #ebeef5;
    border-right: none;
    padding: 20px 0;
    font-size: 15px;
  }

  .el-table__row td {
    border-bottom: 1px solid #ebeef5;
    border-right: none;
    padding: 20px 0;
    background-color: #ffffff;
    font-size: 16px;
  }

.el-table__row:last-child td {
  border-bottom: 1px solid #ebeef5;
}

/* 统一表格单元格样式 */
  .el-table__body-wrapper .el-table__row td,
  .el-table__header-wrapper .el-table__header th {
    padding-left: 0;
    padding-right: 0;
    border-right: none;
  }

  /* 优化列宽分布 */
  .el-table__header th,
  .el-table__body td {
    box-sizing: border-box;
  }
  
  /* 确保角色标识列背景色与表格一致 */
  .el-table__body td:nth-child(3) {
    background-color: #ffffff;
  }
  
  /* 确保表格填满整个区域 */
  .el-table {
    width: 100% !important;
  }

.pagination-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 15px 20px;
  gap: 15px;
  margin-top: 15px;
  margin-bottom: 5px;
}

.pagination-info {
  color: #606266;
  font-size: 16px;
  margin-right: auto;
}

/* 调整分页按钮样式 */
.el-pagination__item {
  margin: 0 2px;
  border-radius: 4px;
  min-width: 32px;
  height: 32px;
  line-height: 32px;
}

.el-pagination__item.is-active {
  background-color: #409eff;
  border-color: #409eff;
  color: #fff;
}

.el-pagination__prev, 
.el-pagination__next {
  min-width: 32px;
  height: 32px;
  line-height: 32px;
  border-radius: 4px;
}

/* 按钮样式优化 */
.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 新增角色按钮容器 */
.add-role-container {
  margin-top: 10px;
  margin-bottom: 5px;
  background-color: #ffffff;
  padding: 10px 15px;
  border-radius: 4px;
}

/* 操作按钮样式 */
.el-button--text {
  color: #409eff;
}

.el-button--text:hover {
  color: #66b1ff;
  background-color: transparent;
  border-color: transparent;
}

.el-button--text:focus {
  color: #66b1ff;
  background-color: transparent;
  border-color: transparent;
}

.el-button--danger:hover {
  background-color: #f78989;
  border-color: #f78989;
}
</style>